/**
 * 按天统计视图组件
 */
class StatsDayView {
    constructor(route) {
        this.route = route;
        this.title = route.title || '按天统计';
        this.chart = null;
        this.table = null;
    }
    
    /**
     * 渲染页面内容
     */
    async render() {
        return `
            <div class="layui-fluid content-wrapper">
                <div class="content-header">
                    <h2>按天统计</h2>
                </div>
                
                <div class="layui-card">
                    <div class="layui-card-header">查询条件</div>
                    <div class="layui-card-body">
                        <form class="layui-form" lay-filter="stats-form">
                            <div class="layui-form-item">
                                <div class="layui-inline">
                                    <label class="layui-form-label">日期范围</label>
                                    <div class="layui-input-inline">
                                        <input type="text" name="startDate" id="startDate" placeholder="开始日期" class="layui-input">
                                    </div>
                                    <div class="layui-form-mid">至</div>
                                    <div class="layui-input-inline">
                                        <input type="text" name="endDate" id="endDate" placeholder="结束日期" class="layui-input">
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label">统计维度</label>
                                    <div class="layui-input-inline">
                                        <select name="dimension" lay-filter="dimension-filter">
                                            <option value="requests">请求数</option>
                                            <option value="bandwidth">带宽使用</option>
                                            <option value="errors">错误数</option>
                                            <option value="latency">平均延迟</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <button class="layui-btn" lay-submit lay-filter="search-btn">
                                        <i class="layui-icon layui-icon-search"></i> 查询
                                    </button>
                                    <button class="layui-btn layui-btn-primary" lay-filter="reset-btn">
                                        <i class="layui-icon layui-icon-refresh"></i> 重置
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                
                <div class="layui-row layui-col-space15">
                    <div class="layui-col-md12">
                        <div class="layui-card">
                            <div class="layui-card-header">按天统计图表</div>
                            <div class="layui-card-body">
                                <div id="dayChart" style="height: 400px;"></div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="layui-row layui-col-space15">
                    <div class="layui-col-md12">
                        <div class="layui-card">
                            <div class="layui-card-header">按天统计数据</div>
                            <div class="layui-card-body">
                                <table class="layui-table" id="dayTable" lay-filter="day-table">
                                    <thead>
                                        <tr>
                                            <th lay-data="{field:'date', width:120, sort:true}">日期</th>
                                            <th lay-data="{field:'requests', width:100, sort:true}">请求数</th>
                                            <th lay-data="{field:'bandwidth', width:120, sort:true}">带宽使用(GB)</th>
                                            <th lay-data="{field:'errors', width:100, sort:true}">错误数</th>
                                            <th lay-data="{field:'latency', width:120, sort:true}">平均延迟(ms)</th>
                                            <th lay-data="{field:'uptime', width:120, sort:true}">可用率(%)</th>
                                        </tr>
                                    </thead>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }
    
    /**
     * 初始化组件
     */
    async init() {
        console.log('按天统计组件初始化');
        
        // 等待DOM加载
        await this.waitForDOM();
        
        // 初始化日期选择器
        this.initDatePicker();
        
        // 初始化图表
        this.initChart();
        
        // 初始化表格
        this.initTable();
        
        // 绑定事件
        this.bindEvents();
        
        // 加载默认数据
        this.loadDefaultData();
        
        // 使用LayUI渲染
        if (typeof layui !== 'undefined') {
            layui.use(['element', 'layer', 'table', 'form', 'laydate'], function() {
                var element = layui.element;
                var layer = layui.layer;
                var table = layui.table;
                var form = layui.form;
                var laydate = layui.laydate;
                
                element.render();
                form.render();
                
                // 渲染日期选择器
                laydate.render({
                    elem: '#startDate',
                    type: 'date',
                    value: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)
                });
                
                laydate.render({
                    elem: '#endDate',
                    type: 'date',
                    value: new Date()
                });
            });
        }
    }
    
    /**
     * 等待DOM加载
     */
    waitForDOM() {
        return new Promise((resolve) => {
            if (document.getElementById('dayChart') && document.getElementById('dayTable')) {
                resolve();
            } else {
                setTimeout(() => resolve(), 100);
            }
        });
    }
    
    /**
     * 初始化日期选择器
     */
    initDatePicker() {
        if (typeof layui !== 'undefined') {
            layui.use(['laydate'], function() {
                var laydate = layui.laydate;
                
                // 开始日期
                laydate.render({
                    elem: '#startDate',
                    type: 'date',
                    value: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
                    done: function(value, date) {
                        // 日期选择完成后的回调
                        console.log('开始日期选择:', value);
                    }
                });
                
                // 结束日期
                laydate.render({
                    elem: '#endDate',
                    type: 'date',
                    value: new Date(),
                    done: function(value, date) {
                        // 日期选择完成后的回调
                        console.log('结束日期选择:', value);
                    }
                });
            });
        }
    }
    
    /**
     * 初始化图表
     */
    initChart() {
        const chartDom = document.getElementById('dayChart');
        if (!chartDom) return;
        
        this.chart = echarts.init(chartDom);
        
        // 设置默认配置
        this.updateChart('requests');
    }
    
    /**
     * 初始化表格
     */
    initTable() {
        if (typeof layui !== 'undefined') {
            layui.use(['table'], function() {
                var table = layui.table;
                
                this.table = table.render({
                    elem: '#dayTable',
                    data: this.generateMockData(),
                    page: true,
                    limit: 10,
                    limits: [10, 20, 50, 100],
                    toolbar: true,
                    defaultToolbar: ['filter', 'exports', 'print'],
                    done: function(res, curr, count) {
                        console.log('表格渲染完成', res, curr, count);
                    }
                });
            }.bind(this));
        }
    }
    
    /**
     * 生成模拟数据 - 已移除
     * 需要连接真实数据接口
     */
    generateMockData() {
        return []; // 静态假数据已移除
    }
    
    /**
     * 格式化日期
     */
    formatDate(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        
        return `${year}-${month}-${day}`;
    }
    
    /**
     * 更新图表 - 移除模拟数据
     * @param {string} dimension - 统计维度
     */
    updateChart(dimension) {
        layer.msg('图表功能需要连接真实数据接口', {icon: 5});
    }
    
    /**
     * 绑定事件
     */
    bindEvents() {
        const self = this;
        
        // 监听搜索表单
        layui.use(['form'], function() {
            var form = layui.form;
            
            form.on('submit(search-btn)', function(data) {
                self.searchData(data.field);
                return false;
            });
            
            form.on('submit(reset-btn)', function() {
                self.resetSearch();
                return false;
            });
            
            form.on('select(dimension-filter)', function(data) {
                self.updateChart(data.value);
            });
        });
        
        // 监听窗口大小变化
        window.addEventListener('resize', () => {
            if (this.chart) {
                this.chart.resize();
            }
        });
    }
    
    /**
     * 搜索数据 - 移除模拟数据
     */
    searchData(params) {
        layer.msg('搜索功能需要连接真实数据接口', {icon: 5});
    }
    
    /**
     * 生成搜索数据
     */
    generateSearchData(startDate, endDate) {
        const data = [];
        const days = Math.ceil((endDate - startDate) / (24 * 60 * 60 * 1000)) + 1;
        
        for (let i = 0; i < days; i++) {
            const date = new Date(startDate.getTime() + i * 24 * 60 * 60 * 1000);
            const requests = Math.floor(Math.random() * 10000) + 5000;
            const errors = Math.floor(Math.random() * requests * 0.1);
            const latency = Math.floor(Math.random() * 100) + 20;
            const bandwidth = (Math.random() * 50 + 10).toFixed(2);
            const uptime = (95 + Math.random() * 4).toFixed(2);
            
            data.push({
                date: this.formatDate(date),
                requests: requests,
                bandwidth: bandwidth,
                errors: errors,
                latency: latency,
                uptime: uptime
            });
        }
        
        return data;
    }
    
    /**
     * 重置搜索
     */
    resetSearch() {
        // 重置表单
        layui.form.val('stats-form', {
            startDate: '',
            endDate: '',
            dimension: 'requests'
        });
        
        // 重新加载默认数据
        this.loadDefaultData();
    }
    
    /**
     * 加载默认数据
     */
    loadDefaultData() {
        const data = this.generateMockData();
        this.updateChartData(data);
        this.updateTableData(data);
    }
    
    /**
     * 更新图表数据
     */
    updateChartData(data) {
        if (this.chart) {
            const dates = data.map(item => item.date);
            const values = data.map(item => item.requests);
            
            this.chart.setOption({
                xAxis: {
                    data: dates
                },
                series: [{
                    data: values
                }]
            });
        }
    }
    
    /**
     * 更新表格数据
     */
    updateTableData(data) {
        if (this.table) {
            this.table.reload({data: data});
        }
    }
    
    /**
     * 清理资源
     */
    destroy() {
        console.log('按天统计组件销毁');
        
        // 销毁图表
        if (this.chart) {
            this.chart.dispose();
            this.chart = null;
        }
        
        // 清理事件监听
        window.removeEventListener('resize', this.resizeChart);
    }
}

// 注册到全局视图组件
if (!window.ViewComponents) {
    window.ViewComponents = {};
}
window.ViewComponents.statsDay = StatsDayView;